/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.abcd.godating.repository.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.inject.Inject;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.abcd.godating.constant.Role;
import com.abcd.godating.domain.Account;
import com.abcd.godating.service.AccountService;

@Repository
public class AccountRepository implements AccountService {

	@Inject
	private JdbcTemplate jdbcTemplate;

	@Inject
	private PasswordEncoder passwordEncoder;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.abcd.godating.repository.IAccount#createAccount(com.abcd.godating
	 * .domain.Account)
	 */
	@Override
	@Transactional
	public Account createAccount(final Account account)
			throws UsernameAlreadyInUseException {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		try {
			jdbcTemplate.update(new PreparedStatementCreator() {
				@Override
				public PreparedStatement createPreparedStatement(
						Connection connection) throws SQLException {
					PreparedStatement ps = connection
							.prepareStatement(
									"insert into Account (username, password, role) values (?,  ?, ?)",
									new String[] { "id" });
					ps.setString(1, account.getUsername());
					ps.setString(2,
							passwordEncoder.encode(account.getPassword()));
					ps.setString(3, account.getRole().name());
					return ps;
				}
			}, keyHolder);
			account.setId((Long) keyHolder.getKey());
			return account;
		} catch (DuplicateKeyException e) {
			throw new UsernameAlreadyInUseException(account.getUsername());
		}
	}

	@Override
	public Account findAccountByUserId(long userId) {
		return jdbcTemplate.queryForObject(
				"select id, username, role from Account where id = ?",
				new RowMapper<Account>() {
					@Override
					public Account mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Account account = new Account();
						account.setId(rs.getLong("id"));
						account.setUsername(rs.getString("username"));
						account.setRole(Role.valueOf(rs.getString("role")));
						return account;
					}
				}, userId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.abcd.godating.repository.IAccount#findAccountByUsername(java.lang
	 * .String)
	 */
	@Override
	public Account findAccountByUsername(String username) {
		return jdbcTemplate.queryForObject(
				"select id, username, role from Account where username = ?",
				new RowMapper<Account>() {
					@Override
					public Account mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Account account = new Account();
						account.setId(rs.getLong("id"));
						account.setUsername(rs.getString("username"));
						account.setRole(Role.valueOf(rs.getString("role")));
						return account;
					}
				}, username);
	}

	@Override
	public void updateAccount(Account account) {
		// TODO Auto-generated method stub

	}

}
